package com.kkkitsch.coolalbum.util;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

	public static String validContent(String content) throws Exception {

		// 客户端对象
		CloseableHttpClient httpclient = getCloseableHttpClient();

		String url = "https://aip.baidubce.com/rest/2.0/antispam/v2/spam?access_token=" + AuthService.getAuth();

		HttpPost httpPost = new HttpPost(url);

		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
		httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

		List<BasicNameValuePair> nameValuePairlist = new ArrayList<BasicNameValuePair>();
		nameValuePairlist.add(new BasicNameValuePair("content", content));

		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairlist, "UTF-8");

		httpPost.setEntity(formEntity);

		CloseableHttpResponse response = httpclient.execute(httpPost);
		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		response.addHeader("Content-Type", "text/html;charset=UTF-8");

		HttpEntity entity = response.getEntity();

		String respContent = EntityUtils.toString(entity, "UTF-8").trim();
		httpPost.abort();
		return respContent;
	}

	public static CloseableHttpClient getCloseableHttpClient() {
		// 客户端对象
		CloseableHttpClient httpclient = null;
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			// 创建一个可以访问https的请求对象
			httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
			return httpclient;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
